import os.path
import demjson
from django.http import JsonResponse
from django.shortcuts import render
from Util import Util, sendWX
from time import time


def Send(requests):
    data = {
        "errcode": -1,
        "msg": "请使用post"
    }
    if requests.method == "POST":
        now = int(round(time() * 1000))
        postdata = demjson.decode(requests.body)
        Util.loger(postdata, level="debug")
        wx = sendWX.wxAPI()
        send_res = wx.send_msg_to_user(postdata["title_data"], str(now))
        if send_res["errcode"]:
            data = {
                "errcode": 1,
                "msg": "发送失败",
                "errmsg": send_res
            }
            return JsonResponse(data)
        else:
            data = {
                "errcode": 0,
                "msg": "发送成功"
            }
        Util.str2html(postdata["msg"], postdata["type"], str(now), Util.templeates_dir)
    return JsonResponse(data)


def Logs(requests, lognum):
    html_file_name = "" + lognum + ".html"
    return render(requests, html_file_name)


def Index(requests):
    README_file_path = os.path.join(os.path.dirname(Util.work_dir), "README.md")
    with open(README_file_path, 'r', encoding='utf-8') as readme_file:
        readme = readme_file.read()
    html_str = Util.str2html(readme, str_type="markdown")
    data = {
        "data": html_str
    }
    return render(requests, "index", data)
